/**
 * 
 */
package com.gr.staffpm.security.role;

import org.apache.wicket.model.LoadableDetachableModel;

import com.gr.staffpm.datatypes.Role;
import com.gr.staffpm.security.service.UserService;


/**
 * @author Graham Rhodes 2 May 2011 20:36:06
 */
public class DetachableRoleModel extends LoadableDetachableModel<Role> {

    private final long id;
    private final UserService userService;
    private static final long serialVersionUID = 1L;

    public DetachableRoleModel(UserService userService, Role r) {
        this(userService, Long.valueOf(r.getRoleId()));
    }

    public DetachableRoleModel(UserService userService, long id) {
        this.userService = userService;
        if (id == 0) {
            throw new IllegalArgumentException();
        }
        this.id = id;
    }

    @Override
    public int hashCode() {
        return Long.valueOf(id).hashCode();
    }

    /**
     * Used for dataview with ReuseIfModelsEqualStrategy item reuse strategy
     * 
     * @see org.apache.wicket.markup.repeater.ReuseIfModelsEqualStrategy
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (obj instanceof DetachableRoleModel) {
            DetachableRoleModel other = (DetachableRoleModel) obj;
            return other.id == id;
        }
        return false;
    }


    @Override
    protected Role load() {
        // loads role from the database
        return userService.getRole((int) id);
    }

}
